package com.itzhigui.config;

import com.itzhigui.interceptor.ApiLoginInterceptor;
import com.itzhigui.interceptor.JWTInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 自定义mvc的配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Resource
    private ApiLoginInterceptor apiLoginInterceptor;

    //处理静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }

    //添加拦截器

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册后端接口使用的拦截器
        registry.addInterceptor(new JWTInterceptor())
                //对哪些路径进行拦截
                .addPathPatterns("/admin/**")
                //刨除不需要拦截的路径
                .excludePathPatterns("/admin/user/login");
        //注册前端接口使用的拦截器
        registry.addInterceptor(apiLoginInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/user/login","/api/user/register","/api/sms/**","/api/**");
    }
    //使用过滤器链条解决跨域，因为过滤器是在拦截器之前执行
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(-1);
        return registrationBean;
    }

}
